package com.example.ymm.config;


import com.example.ymm.component.JwtAuthenticationTokenFilter;
import com.example.ymm.component.RestAuthenticationEntryPoint;
import com.example.ymm.component.RestfulAccessDeniedHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


/**
 * 对SpringSecurity的配置的扩展，支持自定义白名单资源路径和查询用户逻辑
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig  {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private LogoutSuccessHandler logoutSussHandler;




    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

//    @Bean
//    @Override
//    public AuthenticationManager authenticationManagerBean() throws Exception {
//        return super.authenticationManagerBean();
//    }


    // 配置安全过滤链，定义URL访问规则和登录/注销行为
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //放行
        http
                // 关闭CSRF保护（开发环境可关闭，生产环境建议开启）
                .csrf(csrf -> csrf.disable())
                // 配置URL访问授权规则
                .authorizeHttpRequests(auth -> auth
                        // 允许所有人访问首页和静态资源
                        .requestMatchers("/**").permitAll()
                        // 需要ADMIN角色才能访问/admin/**路径
                        .requestMatchers("/admin/**").hasRole("ADMIN")
                        // 其他所有请求都需要认证
                        .anyRequest().authenticated()
                )
                // 配置登录行为
                .formLogin(form -> form
                        // 自定义登录页面（如果需要）
                        .loginPage("/login")
                        // 登录成功后跳转的页面
                        .defaultSuccessUrl("/dashboard", true)
                        // 允许所有人访问登录页面
                        .permitAll()
                )
                // 配置注销行为
                .logout(logout -> logout
                        // 注销成功后跳转的页面
                        .logoutSuccessUrl("/")
                        // 允许所有用户注销
                        .permitAll()
                );

        return http.build();
    }

    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
        return new RestfulAccessDeniedHandler();
    }

    @Bean
    public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
        return new RestAuthenticationEntryPoint();
    }

    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig() {
        return new IgnoreUrlsConfig();
    }

//    @Bean
//    public JwtTokenUtil jwtTokenUtil() {
//        return new JwtTokenUtil();
//    }

    /*public static void main(String[] args) {
        //密码加密方式
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(bCryptPasswordEncoder.encode("test"));
    }*/
}
